import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import dayjs from 'dayjs';
import SwitchBar from './components/SwitchBar';
import SwitchWeekBar from './components/SwitchWeekBar';
import WeekBar from './components/WeekBar';
import DayGrid from './components/DayGrid';
import LessTwoWeekGrid from './components/LessTwoWeekGrid';
import LessTwoMonthGrid from './components/LessTwoMonthGrid';
import styles from './index.module.less';

// TODO 需要简化

const SelectedTimeShow = (props) => {
  const { className, dateTimeList, range } = props;

  const [firstDay, setFirstDay] = useState(null);

  const [type, setType] = useState(null);

  useEffect(() => {
    if (range) {
      setFirstDay(dayjs(range[0]));
      getDays();
    } else if (dateTimeList) {
      setFirstDay(dayjs(dateTimeList[0]));
    } else {
      setFirstDay(dayjs());
    }
  }, [range, dateTimeList]);

  const onSwitchMonth = (tag) => {
    if (tag === 'prev') {
      setFirstDay(firstDay.add(-1, 'month'));
    }
    if (tag === 'next') {
      setFirstDay(firstDay.add(1, 'month'));
    }
  };

  const onSwitchWeek = (tag) => {
    if (tag === 'prevWeek') {
      setFirstDay(firstDay.add(-1, 'week'));
    }
    if (tag === 'nextWeek') {
      setFirstDay(firstDay.add(1, 'week'));
    }
  };

  const getDays = () => {
    if (range && Array.isArray(range)) {
      const [l, r] = range;
      if (l && r) {
        const ld = dayjs(l);
        const rd = dayjs(r);
        const ds = rd.diff(ld, 'day');
        if (ds >= 60) {
          setType('month');
        } else if (ds >= 14) {
          setType('week');
        } else if (ds > 1) {
          setType('day');
        }
      }
    } else {
      setType(null);
    }
  };

  return (
    <div className={classnames(styles.root, className)}>
      {type === 'month' ? (
        <SwitchBar date={firstDay} range={range} onClick={onSwitchMonth} />
      ) : type === 'week' ? (
        <SwitchWeekBar date={firstDay} range={range} onClick={onSwitchWeek} />
      ) : null}
      <WeekBar />
      {type === 'month' || type === null ? (
        <DayGrid date={firstDay} dateList={dateTimeList} />
      ) : type === 'week' ? (
        <LessTwoMonthGrid date={firstDay} dateList={dateTimeList} />
      ) : type === 'day' ? (
        <LessTwoWeekGrid date={firstDay} dateList={dateTimeList} />
      ) : null}
    </div>
  );
};

SelectedTimeShow.defaultProps = {
  className: null,
  dateTimeList: null,
  range: null,
};

SelectedTimeShow.propTypes = {
  className: PropTypes.any,
  dateTimeList: PropTypes.any,
  range: PropTypes.any,
};

export default SelectedTimeShow;
